package cn.com.fuhuitong.main.cart.ui.fragment

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.SimpleItemAnimator
import cn.com.fuhuitong.app.BaseApplication
import cn.com.fuhuitong.base.EmptyContent
import cn.com.fuhuitong.entity.EmptyState
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeFragment
import cn.com.fuhuitong.main.cart.vm.CartViewModel
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.alibaba.android.vlayout.layout.StickyLayoutHelper
import com.blankj.utilcode.util.LogUtils
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.entity.CartState
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.MainType
import cn.com.fuhuitong.main.access.ui.fragment.AccessAccountFragment
import cn.com.fuhuitong.main.cart.adapter.CVT
import cn.com.fuhuitong.main.cart.adapter.CartBottomAdapter
import cn.com.fuhuitong.main.cart.adapter.CartGoodsAdapter
import cn.com.fuhuitong.main.cart.entity.CartListEntity
import cn.com.fuhuitong.main.order.entity.SubmitConfirmEntity
import cn.com.fuhuitong.main.order.entity.SubmitConfirmGoods
import cn.com.fuhuitong.utils.SpanUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import kotlinx.android.synthetic.main.fragment_main_cart.*
import kotlinx.android.synthetic.main.fragment_order_list.*
import org.greenrobot.eventbus.EventBus


class CartFragment : ViewModeFragment<CartViewModel>() {

    companion object {
        private val IS_SHOW_BACK = "isShowBack"
        fun newInstance(isShowBack: Boolean = false): CartFragment {
            return CartFragment().apply {
                arguments = Bundle().apply {
                    putBoolean(IS_SHOW_BACK, isShowBack)
                }
            }
        }
    }


    enum class Action {
        PLUS, REDUCE
    }

    private var position: Int = 0
    private var action: Action = Action.PLUS

    private var isDeleteItem = true


    override fun viewModel(): CartViewModel = ViewModelProvider(
        requireActivity(),
        ViewModelProvider.AndroidViewModelFactory(BaseApplication.INSTANCE)
    ).get(CartViewModel::class.java)

    override val layoutResId: Int
        get() = R.layout.fragment_main_cart

    override fun initView() {

        if (arguments?.getBoolean(IS_SHOW_BACK, false) == true) {
            image_cart_back.visibility = View.VISIBLE
            image_cart_back.setOnClickListener {
                requireActivity().finish()
            }
        } else {
            image_cart_back.visibility = View.GONE
        }

        this.initViewRecyclerAdapter(with(recycler_cart_goods) {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            isFocusableInTouchMode = false
            this
        }, arrayOf(CVT.CART_GOODS.ordinal))

        delegateAdapter.addAdapter(initViewCartGoodsAdapter().apply {
            cartGoodsAdapter = this
        })

        cartGoodsAdapter.setOnItemChildClickListener { view, position, cartListEntity ->
            this.position = position
            if (view.id == R.id.text_goods_plus) {
                viewModel.cartUpdateNum(
                    cartListEntity.id.toString(), (cartListEntity.num + 1).toString()
                ).apply {
                    action = Action.PLUS
                }
            } else if (view.id == R.id.text_goods_reduce) {
                viewModel.cartUpdateNum(
                    cartListEntity.id.toString(), (cartListEntity.num - 1).toString()
                ).apply {
                    action = Action.REDUCE
                }
            } else if (view.id == R.id.text_goods_delete) {
                isDeleteItem = true
                recycler_cart_goods.closeMenu()
                viewModel.cartDelete(arrayListOf(cartListEntity.id.toString()))
            }
        }

        cartGoodsAdapter.cartListDataLiveData.observe(this, Observer {
            cartPriceCalculation(it)
        })


        check_cart_edit.setOnCheckedChangeListener { _, isChecked ->
            check_cart_edit.text = if (isChecked) "编辑" else "完成"
            cartGoodsAdapter.postValue()
        }

        text_cart_go_settlement.setOnClickListener {
            if (check_cart_edit.isChecked) {
                //去结算
                val submitConfirmGoods = arrayListOf<SubmitConfirmGoods>()
                cartGoodsAdapter.getSelectedItem().forEach {
                    submitConfirmGoods.add(
                        SubmitConfirmGoods(
                            it.goods_id.toString(),
                            it.num.toString(),
                            it.specifications_id.toString()
                        )
                    )
                }
                val submitConfirmEntity = SubmitConfirmEntity(submitConfirmGoods)
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_SUBMIT)
                    .withSerializable(AppConstance.BUNDLE_SUBMIT_CONFIRM, submitConfirmEntity)
                    .navigation()
            } else {
                //删除操作
                isDeleteItem = false
                val shopCartIds = arrayListOf<String>()
                for ((index: Int, entity: CartListEntity) in
                cartGoodsAdapter.getSelectedItem().withIndex()) {
                    shopCartIds.add(entity.id.toString())
                }
                viewModel.cartDelete(shopCartIds)
            }
        }

        check_cart_total_select.setOnClickListener {
            check_cart_total_select.isChecked = !check_cart_total_select.isChecked
            cartGoodsAdapter.setSelectedTotal(!check_cart_total_select.isChecked)
        }
    }

    private fun cartPriceCalculation(entity: MutableList<CartListEntity>) {
        var price = 0.0
        entity.forEach {
            price += if (it.is_specifications == 1) {
                if (it.member_discount_price == 0.0)
                    (if (it.specifications_price != null) it.specifications_price.toDouble() else 0.0) * it.num
                else it.member_discount_price * it.num
            } else {
                if (it.member_discount_price == 0.0) it.price.toDouble() * it.num
                else it.member_discount_price * it.num
            }

//            price +=it.price.toDouble() * it.num
        }
        with(text_cart_total_price) {
            text = if (price == 0.0) "" else SpanUtils.setMoneyStyle(price)
        }
        with(check_cart_total_select) {
            text = if (entity.size == 0) "全选" else "已选(${entity.size})"
            isChecked =
                if (cartGoodsAdapter.data.size == 0) false else entity.size == cartGoodsAdapter.data.size
        }
        with(text_cart_go_settlement) {
            isEnabled = entity.size != 0
            text = if (check_cart_edit.isChecked) "去结算" else "删除"
        }
        text_cart_total_price.visibility =
            if (check_cart_edit.isChecked) View.VISIBLE else View.GONE
    }

    override fun initViewMode() {
        viewModel.cartListDataLiveData.observe(this, Observer { response ->
//            handlerResponseEmpty(
//                status = response.status, message = response.statusTip,
//                length = response.response?.data?.size ?: 0,
//                emptyContent = EmptyContent("去逛逛", "您还没有添加任何商品哦~")
//            )


            val dataLength: Int = response.response?.data?.size ?: 0

            when (response.status) {
                HttpResponseStatus.Status.START -> {
                    if (dataLength == 0) {
                        showLoadEmptyView()
                    }
                }
                HttpResponseStatus.Status.SUCCESS -> {
                    if (dataLength == 0) {
                        check_cart_edit.visibility = View.GONE
                        constraint_cart_bottom.visibility = View.GONE
                        showNullEmptyView(EmptyContent("去逛逛", "您还没有添加任何商品哦~"))
                    } else {
                        check_cart_edit.visibility = View.VISIBLE
                        constraint_cart_bottom.visibility = View.VISIBLE
                        hideEmptyView()
                    }
                }
                HttpResponseStatus.Status.FAILURE -> {
                    if (dataLength == 0) {
                        showErrorEmptyView(EmptyContent("重新加载", response.statusTip))
                    }
                    toast(response.statusTip)
                }
            }

            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                if (it.size == 0)
                    return@let
                cartGoodsAdapter.setAddDataNew(it)
                check_cart_edit.visibility = View.VISIBLE
                constraint_cart_bottom.visibility = View.VISIBLE
            }
        })

        viewModel.cartUpdateNumDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            cartGoodsAdapter.upDataItem(action, position)
            cartGoodsAdapter.postValue()
        })

        viewModel.cartDeleteDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            if (isDeleteItem) {
                cartGoodsAdapter.deleteItem(position)
            } else {
                cartGoodsAdapter.deleteItem(cartGoodsAdapter.getSelectedItem())
            }
            cartGoodsAdapter.postValue()

            if (cartGoodsAdapter.data.size == 0) {
                check_cart_edit.visibility = View.GONE
                constraint_cart_bottom.visibility = View.GONE
                showNullEmptyView(EmptyContent("去逛逛", "您还没有添加任何商品哦~"))
            }
        })
    }

    override fun initData() {
        viewModel.cartList()
    }


    override fun onRefreshLoad() {
        viewModel.cartList()
    }

    override fun onLoadingEmptyView(state: EmptyState) {
        super.onLoadingEmptyView(state)
        if (state == EmptyState.FAILURE) {
            viewModel.cartList()
        } else if (state == EmptyState.NULL) {
            EventBus.getDefault().post(
                MainBean(type = MainType.HOME, data = null)
            )

        }
    }

    /**
     * 初始化购物车物品适配器
     * */
    private lateinit var cartGoodsAdapter: CartGoodsAdapter
    private fun initViewCartGoodsAdapter(): CartGoodsAdapter {
        val helper = LinearLayoutHelper()
        helper.setDividerHeight(
            requireActivity().resources.getDimensionPixelSize(R.dimen.dp_10)
        )
        return CartGoodsAdapter(
            requireContext(), helper
        )
    }

    /**
     * 初始化购物车底部适配器
     * */
    private lateinit var cartBottomAdapter: CartBottomAdapter
    private fun initViewCartBottomAdapter(): CartBottomAdapter {
        val helper = StickyLayoutHelper(false)
        return CartBottomAdapter(
            requireContext(), helper
        )
    }

}